using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using DecisionMaking.BusinessLogic;
using DecisionMaking.Domain;
using System.Web.Security;
using MvcContrib;
using Controllers;
using DecisionMaking.BusinessLogic.Model;

namespace DecisionMaking.WebApp
{
	/// <summary>
	/// Responsible for all Account operations, including Login, Logout, Register and profile editing
	/// </summary>
	[HandleError]
	public class AccountController : BaseController
	{
		
		[HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
				try 
				{
              		AccountManager.Register(model);
					
					return this.RedirectToAction<HomeController>(c => c.Index());
				}
				catch (DuplicateEmailException e)
				{
					ModelState.AddModelError("Email", "This email address is already in use");
				}
            }
			
			// if we've reached here, form validation failed so we should return to the form
			return View(model);			
        }
		
		[HttpGet]
        public ActionResult Login()
        {
            return View();
        }	
		
		[HttpPost]
        public ActionResult Login(LoginModel model)
        {
        	if (ModelState.IsValid)    
			{
				try
				{
					Account account = AccountManager.GetAccountByCredentials(model.Email, model.Password);
				
					DoLogin(account, model.RememberMe);
						
					return this.RedirectToAction<HomeController>(c => c.Index());
				}
				catch (AccountNotFoundException e)
				{
					ModelState.AddModelError("Email", e);
				}
			}

			return View(model);
			
        }	
		
		[HttpGet]
		public ActionResult Logout()
		{
			FormsAuthentication.SignOut();
			
			return this.RedirectToAction<HomeController>(c => c.Index());
		}
		
		
		/// <summary>
		/// Performs a login against the ASP.NET security namespace 
		/// </summary>
		private void DoLogin(Account account, bool rememberMe) 
		{
			FormsAuthentication.SetAuthCookie(account.Email, rememberMe);
			
			// save account in session
			this.CurrentAccount = account;
			
			//TODO set IPrincipal in the HttpContext
		}
		
	}
}

